package com.RWM.activities;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONException;
import org.json.JSONObject;

import com.RWM.serverTools.Connect;
import com.RWM.reference.Reference;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	private Button btnlogin;
	private Button btncancel;
	private Button btnregister;
	private Toast toast;
	private Connect client;
	private String res;
	private Intent myIntent;
	HttpPost httppost;
	HttpClient httpclient;
	RideWithMe context;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
	
		
		/* Get all my buttons and add a listener */
		btnlogin = (Button) findViewById(R.id.btn_login);
//		btncancel = (Button) findViewById(R.id.btn_logout);
		btnregister = (Button) findViewById(R.id.btn_register);
		btnlogin.setOnClickListener(this);
//		btncancel.setOnClickListener(this);
		btnregister.setOnClickListener(this);
	} //END onCreate
	

	public void onClick(View v){
		switch (v.getId()){

//		WHEN SERVER WORKS, UNCOMMMENT THIS SECTION AND REMOVE THIS COMMENT
//		case R.id.btn_login: /* Go to the next screen */
//			myIntent = new Intent(LoginActivity.this, HomeActivity.class);
//
//			EditText name = (EditText) findViewById(R.id.log_username);
//			EditText password = (EditText) findViewById(R.id.log_password);
//
//			//Checking for null data in the username or password fields
//			if(checkForNull(name, password)) {
//				Toast.makeText(LoginActivity.this, "Please enter Username and/or Password",
//						Toast.LENGTH_LONG).show();
//			}
//
//
//			//Username and password fields are NOT blank
//			else {
//
//				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
//
//				// Adding parameters to send to the HTTP server for login.
//				nameValuePairs.add(new BasicNameValuePair("user", name.getText().toString()));
//				nameValuePairs.add(new BasicNameValuePair("pw", password.getText().toString()));
//
//				String response = userLogin(nameValuePairs);
//
//				JSONObject json = createJSON(response);
//
//				//http post returned null meaning bad username/password
//				if(json==null){
//					Toast.makeText(LoginActivity.this, "Invalid username/password",
//							Toast.LENGTH_LONG).show();
//				}
//
//				else{
//					Log.v("test", json.toString());	
//					myIntent.putExtra("json", json.toString());
//					startActivity(myIntent);
//
//				}
//
//			}
//
//			break;
		/**
		 * TEMPORARY CODE FOR TEST
		 * START POINT
		 */
		case R.id.btn_login:
		myIntent = new Intent(LoginActivity.this, HomeActivity.class);
		/* Mocked up json */
		JSONObject json = createJSON("{'access_token':'359e408a5a39f1b5828de829bd835031','refresh_token':'ae3d318ca1e2a6cdc209630e8bf890e9'}");
		try {
			myIntent.putExtra("access_token", json.getString("access_token"));
		} catch (JSONException e1) {
			
			Log.v("json", "Could not retreive \"access_token\" field from JSON");
		}
			
	      /*
         * Only call authorize if the access_token has expired.
         */
		
    
		
		startActivity(myIntent);
		break;
		
		/**
		 * TEMPORARY CODE FOR TEST
		 * END POINT
		 */

		case R.id.btn_register:
			myIntent = new Intent(getApplicationContext(), RegisterActivity.class);
			startActivity(myIntent);
			break;

//		case R.id.btn_logout: /* Test my restful api */
//			client = new Connect("http://68.184.90.31/syncweb/service/dowork");
//			client.AddParam("id", "Daranh");
//			try { /* Execute the response and popup the response to the user. */
//				client.Execute(Reference.RequestMethod.GET);
//				res = client.getResponse();
//				toast.makeText(this, res, Toast.LENGTH_LONG).show();
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			break;
		}

	}

	public JSONObject createJSON(String json) {
		JSONObject jObj = null;
		try {
			//Log.v("test", json);
			jObj = new JSONObject(json);
		} 

		catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;
	}

	public String userLogin(List<NameValuePair> nameValuePairs){

		String url = "http://m.cip.gatech.edu/developer/imf/api/RWMSERVER/login";
		String serverResponsePhrase;
		int serverStatusCode=-1;
		String bytesSent="null";
		HttpPost httppost = new HttpPost(url);
		DefaultHttpClient httpclient = new DefaultHttpClient();

		// Send POST message  with given parameters to the HTTP server.
		try {                    
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

			HttpResponse response = httpclient.execute(httppost);

			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(20);

			int current = 0;  
			while((current = bis.read()) != -1) {  
				baf.append((byte)current);  
			}  

			bytesSent = new String(baf.toByteArray());

			// Response from the server          
			serverResponsePhrase = response.getStatusLine().getReasonPhrase();
			serverStatusCode = response.getStatusLine().getStatusCode();

			//Log.v("test", serverResponsePhrase);
			//Log.v("test", String.valueOf(serverStatusCode));
			//Log.v("test", String.valueOf(bytesSent));
			return bytesSent;

		}
		catch (Exception e) {
			Log.e("test", "An error occured while trying to create a user");			
		}
		return bytesSent;
	}

	public boolean checkForNull(EditText name, EditText password) {
		if(name.getText().toString().compareTo("")==0 || password.getText().toString().compareTo("")==0){
			return true;
		}
		else {
			return false;
		}
	}

}